package pub.tbc.api.invoker.protocol.http;

import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.api.invoker.AbstractInvoker;
import pub.tbc.api.service.ServiceInfo;
import pub.tbc.api.service.discovery.DiscoveryFactory;
import pub.tbc.api.service.discovery.ServiceDiscovery;
import pub.tbc.api.service.mapping.ServiceMapping;
import pub.tbc.api.service.mapping.ServiceMappingProvider;

import java.net.InetSocketAddress;

/**
 * @author tbc on 2017/3/3 16:50:32.
 */
@Slf4j
public abstract class AbstractHttpInvoker extends AbstractInvoker {
    protected ServiceMapping serviceMapping = ServiceMappingProvider.getServiceParse();
    protected ServiceDiscovery discovery = DiscoveryFactory.getServiceDiscovery();

    protected String serviceAddress(ServiceInfo serviceInfo) {
        return discovery.discover(serviceInfo.getServiceName());
    }

    protected InetSocketAddress serviceAddress0(String serviceAddress) {
        String[] array = serviceAddress.split(":");
        String host = array[0];
        int port = Integer.parseInt(array[1]);
        return InetSocketAddress.createUnresolved(host, port);
    }

    protected ServiceInfo serviceInfo(FullHttpRequest request) {
        return serviceMapping.map(request);
    }

    protected String requestToString(FullHttpRequest request) {
        return "Host: " + request.headers().get("Host") + ", uri: " + request.uri();
    }
}
